const TurtleTradingSystem = require('./turtle-trading');

async function runBacktest() {
    console.log('启动海龟交易法则回测...\n');

    // 创建交易系统实例
    const turtle = new TurtleTradingSystem(100000);

    try {
        // 运行回测
        const results = await turtle.backtest(
            'AAPL', 
            '2020-01-01', 
            '2023-12-31'
        );

        // 生成报告
        const report = turtle.generateReport(results);

        // 显示前10笔交易
        console.log('\n=== 前10笔交易记录 ===');
        results.trades.slice(0, 10).forEach((trade, index) => {
            console.log(`${index + 1}. ${trade.date} ${trade.action} ${trade.shares}股 @ $${trade.price.toFixed(2)} (系统${trade.system})`);
        });

        // 显示性能摘要
        console.log('\n=== 性能摘要 ===');
        console.log(`夏普比率: ${calculateSharpeRatio(results.portfolio).toFixed(2)}`);
        console.log(`波动率: ${calculateVolatility(results.portfolio).toFixed(2)}%`);

    } catch (error) {
        console.error('回测失败:', error);
    }
}

// 计算夏普比率 (简化版)
function calculateSharpeRatio(portfolio) {
    const returns = [];
    for (let i = 1; i < portfolio.length; i++) {
        const dailyReturn = (portfolio[i].totalValue - portfolio[i-1].totalValue) / portfolio[i-1].totalValue;
        returns.push(dailyReturn);
    }
    
    const avgReturn = returns.reduce((a, b) => a + b, 0) / returns.length;
    const stdDev = Math.sqrt(returns.reduce((acc, ret) => acc + Math.pow(ret - avgReturn, 2), 0) / returns.length);
    
    return stdDev > 0 ? (avgReturn / stdDev) * Math.sqrt(252) : 0;
}

// 计算波动率
function calculateVolatility(portfolio) {
    const returns = [];
    for (let i = 1; i < portfolio.length; i++) {
        const dailyReturn = (portfolio[i].totalValue - portfolio[i-1].totalValue) / portfolio[i-1].totalValue;
        returns.push(dailyReturn);
    }
    
    const avgReturn = returns.reduce((a, b) => a + b, 0) / returns.length;
    const variance = returns.reduce((acc, ret) => acc + Math.pow(ret - avgReturn, 2), 0) / returns.length;
    
    return Math.sqrt(variance * 252) * 100;
}

// 运行示例
runBacktest();